<template>
  <div>
    <contentModel
      v-if="viewDetailShow"
      title="供应商信息"
      :class="screenClass"
      :has-footer="false"
      @close="handleClose"
    >
      <table-container
        v-model:columns="columns"
        v-model:is-fullscreen="isFullscreen"
        :loading="isLoadin"
        :all-columns="allColumns"
        @refresh="getData"
      >
        <template #container-side>
          <a-space>
            <a-button
              v-permission="['procurement:plan-supplier:batchSaveOrUpdate']"
              type="primary"
              @click="handleAdd"
            >
              添加
            </a-button>
            <a-button
              v-if="activeRadio === '5'"
              v-permission="['procurement:plan-supplier:doWBid']"
              :disabled="selectedKeys.length === 0"
              @click="handleBid"
            >
              中标
            </a-button>
            <a-button
              v-if="activeRadio === '5'"
              v-permission="['procurement:plan-supplier:doNWBid']"
              :disabled="selectedKeys.length === 0"
              @click="handleCancelBid"
            >
              取消中标
            </a-button>
            <a-button
              v-permission="['procurement:plan-supplier:delete']"
              :disabled="selectedKeys.length === 0"
              @click="handleDelete"
            >
              删除
            </a-button>
            <a-button
              v-permission="[
                'procurement:excel-operation:exportZtb',
                'procurement:excel-operation:exportCompeteNegotiation',
                'procurement:excel-operation:exportBxcg',
              ]"
              @click="exportCpWzdapi"
            >
              Excel导出
            </a-button>
            <a-button
              v-permission="[
                'procurement:excel-operation:importZtb',
                'procurement:excel-operation:importCompeteNegotiation',
                'procurement:excel-operation:importBxcg',
              ]"
              @click="handleExcel"
            >
              Excel导入
            </a-button>
          </a-space>
        </template>
        <standard-table
          v-model:selectedKeys="selectedKeys"
          :component-config="tableComponentConfig"
          :render-config="tableRenderConfig"
          :render-keys="tableRenderKeys"
          :loading="isLoadin"
          :data="renderData"
          :total="total"
          row-selection-type="checkbox"
          :columns="columns"
          @init-columns-end="initColumns"
        >
          <template #operate="{ record }">
            <a-button
              v-permission="['procurement:plan-supplier:batchSaveOrUpdate']"
              type="text"
              @click="handleEdit(record)"
            >
              编辑
            </a-button>
          </template>
        </standard-table>
      </table-container>
    </contentModel>

    <a-modal
      :visible="popVisible"
      width="50vw"
      title-align="start"
      :title="titleValue"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form
        ref="formRef"
        :model="addForm"
        :rules="formRules"
        auto-label-width
      >
        <a-row :gutter="16">
          <a-col :span="8"
            ><a-form-item field="inputType" label="录入类型：">
              <dict-select
                v-model="addForm.inputType"
                allow-clear
                dict-type="inputType"
                placeholder="请选择"
                @change="execChange"
              ></dict-select> </a-form-item
          ></a-col>
          <a-col :span="8"
            ><a-form-item
              v-if="activeRadio !== '5'"
              field="pmsInvTaxPrice"
              label="含税结算单价："
            >
              <a-input-number
                v-model="addForm.pmsInvTaxPrice"
                placeholder=""
                :disabled="addForm.inputType === '0'"
                @blur="execChange"
              /> </a-form-item
          ></a-col>
          <a-col :span="8"
            ><a-form-item
              v-if="activeRadio !== '5'"
              field="pmsBalancePrice"
              label="不含税结算单价："
            >
              <a-input-number
                v-model="addForm.pmsBalancePrice"
                placeholder=""
                :disabled="addForm.inputType === '1'"
                @blur="execChange"
              /> </a-form-item
          ></a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8"
            ><a-form-item field="supplierCode" label="供应商编码：">
              <inputModal
                v-model="addForm.supplierCode"
                :label-value="addForm.supplierCode"
                :value-name="'supplierCode'"
                :title="'供应商编码'"
                :type="'supplyName'"
                :default-query="{
                  secretLevel,
                }"
                @handle-ok="selectSupplier"
              /> </a-form-item
          ></a-col>
          <a-col :span="8">
            <a-form-item field="supplierName" label="供应商名称：">
              <a-input v-model="addForm.supplierName" placeholder="" disabled />
            </a-form-item>
          </a-col>
          <a-col :span="8"
            ><a-form-item field="supplierLinkmanTel" label="供应商联系电话：">
              <a-input
                v-model="addForm.supplierLinkmanTel"
                placeholder=""
              /> </a-form-item
          ></a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8"
            ><a-form-item field="supplierLinkmanName" label="供应商联系人：">
              <inputModal
                v-model="addForm.supplierLinkmanName"
                :label-value="addForm.supplierLinkmanName"
                value-name="contacts"
                label-name="contacts"
                :disabled="!addForm.supplierCode"
                title="供应商联系人"
                type="supplyPerson"
                :default-query="{
                  supplierCode: addForm.supplierCode,
                }"
                @show-tips="vendorLinkManTips"
                @handle-ok="vendorLinkManChange"
              >
              </inputModal> </a-form-item
          ></a-col>
          <a-col :span="8"
            ><a-form-item field="exTaxPrice" label="不含税单价：">
              <a-input-number
                v-model="addForm.exTaxPrice"
                placeholder=""
                :disabled="addForm.inputType === '1'"
                @blur="execChange"
              /> </a-form-item
          ></a-col>
          <a-col :span="8"
            ><a-form-item field="pmsEstimatePrice" label="预估价：">
              <a-input-number
                v-model="addForm.pmsEstimatePrice"
                placeholder=""
              /> </a-form-item
          ></a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8"
            ><a-form-item field="invPurQty" label="采购数量（采购）：">
              <a-input-number
                v-model="addForm.invPurQty"
                placeholder=""
                @blur="execChange"
              /> </a-form-item
          ></a-col>
          <a-col :span="8"
            ><a-form-item field="taxRateCode" label="税率：">
              <dict-select
                v-model="addForm.taxRateCode"
                style="width: 500px"
                allow-clear
                dict-type="taxRate"
                placeholder="请选择"
                @change="changeSelect"
              ></dict-select> </a-form-item
          ></a-col>
          <a-col :span="8"
            ><a-form-item field="currencyType" label="币种：">
              <dict-select
                v-model="addForm.currencyType"
                style="width: 500px"
                allow-clear
                dict-type="currencyType"
                placeholder="请选择"
              ></dict-select> </a-form-item
          ></a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8"
            ><a-form-item field="pmsMdsUnitCode" label=" 计量单位（采购）：">
              <dict-select
                v-model="addForm.pmsMdsUnitCode"
                allow-clear
                dict-type="unitOfMeasurement"
                placeholder="请选择"
                @change="changeSelect"
              ></dict-select> </a-form-item
          ></a-col>
          <a-col :span="8"
            ><a-form-item field="taxPrice" label="含税单价：">
              <a-input-number
                v-model="addForm.taxPrice"
                placeholder=""
                :disabled="addForm.inputType === '0'"
                @blur="execChange"
              /> </a-form-item
          ></a-col>
          <a-col :span="8"
            ><a-form-item
              v-if="activeRadio !== '5'"
              field="choiceTage"
              label="选择结果："
            >
              <a-select v-model="addForm.choiceTage" placeholder="请选择">
                <a-option
                  v-for="item of dictList2"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                />
              </a-select> </a-form-item
          ></a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8"
            ><a-form-item field="pmsInvPrice" label=" 库存单价：">
              <a-input-number
                v-model="addForm.pmsInvPrice"
                placeholder=""
                disabled /></a-form-item
          ></a-col>
          <a-col :span="8"
            ><a-form-item field="pmsInvQty" label="库存数量：">
              <a-input-number
                v-model="addForm.pmsInvQty"
                placeholder=""
                disabled
              /> </a-form-item
          ></a-col>
          <a-col :span="8"
            ><a-form-item field="measureUnit" label="基本计量单位">
              <dict-select
                v-model="addForm.measureUnit"
                disabled
                dict-type="unitOfMeasurement"
              ></dict-select></a-form-item
          ></a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8"
            ><a-form-item field="mdsUintRate" label="转换系数：">
              <a-input-number
                v-model="addForm.mdsUintRate"
                :min="1"
                placeholder=""
                @blur="execChange"
              /> </a-form-item
          ></a-col>
          <a-col :span="8"
            ><a-form-item field="note" label="备注：">
              <a-input v-model="addForm.note" placeholder="" /> </a-form-item
          ></a-col>
        </a-row>
      </a-form>
    </a-modal>
    <!-- 批量上传 -->
    <batchImport
      v-if="batchVisible"
      export-type="apiUrl"
      :file-code="excelObj[activeRadio].code"
      :import-url="excelObj[activeRadio].importurl"
      :export-url="excelObj[activeRadio].exportUrl"
      :params="{ planListNo }"
      @close-drawer="closeDrawer"
      @finish="finish"
    ></batchImport>
  </div>
</template>

<script lang="ts" setup>
  import batchImport from '@/common/components/batch-import/import-container.vue';
  import StandardTable from '@/common/components/standard-table/index.vue';
  import tableContainer from '@/common/components/table-container/index.vue';
  import { defineAsyncComponent, ref } from 'vue';
  import {
    pageByPlanListNo, // 获取子表单数据
    checkTender,
    batchSaveOrUpdate,
    plansupplier,
    exportBxcg, // 比选采购 导出
    exportCompeteNegotiation, // 竞争性谈判 导出
    exportZtb, // 招投标 导出
    doWBid,
    doNWBid,
    execCalculate,
  } from '@/api/supplier/selective-quotient';
  import lodash from 'lodash';
  import useFullScreen from '@/common/hooks/fullScreen';
  import { Message, Modal } from '@arco-design/web-vue';
  import dictSelect from '@/common/components/dict-select/index.vue';
  import inputModal from '@/common/components/search-modal/input-modal.vue';
  import { downFileToExcel } from '@/common/utils/downFile';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from './tableComp/baseTableConfig';

  const allColumns = ref<object[]>([]);
  const { isFullscreen, screenClass } = useFullScreen();
  const selectedKeys = ref<any[]>([]);
  const contentModel = defineAsyncComponent(
    () => import('@/common/components/content-model/index.vue')
  );
  const popVisible = ref(false);
  const tableRenderKeys = ref();
  const renderData = ref<any[]>([]);
  // 选商方式确认子表单api
  const columns = ref<object[]>([]);
  const total = ref();
  const dictList2 = ref([
    {
      label: '是',
      value: 1,
    },
    {
      label: '否',
      value: 0,
    },
  ]);
  const titleValue = ref('');
  const addForm = ref({
    serialnumber: '',
    supplierLinkmanName: '',
    supplierLinkmanTel: '',
    pmsInvPrice: 0,
    pmsInvQty: 0,
    mdsUintRate: 1,
    invPurQty: 0,
    pmsMdsUnitCode: '',
    inputType: '0',
    pmsBalancePrice: 0,
    exTaxPrice: 0,
    taxPrice: 0,
    pmsInvTaxPrice: 0,
    pmsEstimatePrice: 0,
    currencyType: '',
    choiceTage: '',
    note: '',
    taxRateCode: '',
    supplierName: '',
    supplierCode: '',
  });
  const formRules = ref({
    pmsMdsUnitCode: [
      {
        required: true,
        message: '计量单位不能为空',
        trigger: 'change',
      },
    ],
    mdsUintRate: [
      {
        required: true,
        message: '请输入转换系数',
        trigger: 'change',
      },
    ],
    currencyType: [
      {
        required: true,
        message: '请选择币种',
        trigger: 'change',
      },
    ],
    inputType: [
      {
        required: true,
        message: '请输入录入类型',
        trigger: 'change',
      },
    ],
    taxRateCode: [
      {
        required: true,
        message: '请选择税率',
        trigger: 'change',
      },
    ],
    supplierCode: [
      {
        required: true,
        message: '请选择供应商编码',
        trigger: 'change',
      },
    ],
  });
  defineProps({
    viewDetailShow: { type: Boolean, default: false },
  });
  const activeRadio = ref();
  const isLoadin = ref(false); // 子级表格控制loading状态
  const emit = defineEmits(['update:viewDetailShow']);
  const handleEdit = (record) => {
    addForm.value = Object.assign(addForm.value, record);
    titleValue.value = '编辑';
    popVisible.value = true;
  };
  const handleAdd = async () => {
    if (activeRadio.value === '5') {
      const { data } = await checkTender(planListNo.value);
      if (!data) {
        Message.warning('请先填写招投标信息');
      }
    }
    titleValue.value = '添加';
    addForm.value = Object.assign(addForm.value, {
      serialnumber: '',
      supplierLinkmanName: '',
      supplierLinkmanTel: '',
      pmsInvPrice: 0,
      pmsInvQty: 0,
      mdsUintRate: 1,
      invPurQty: 0,
      pmsMdsUnitCode: '',
      inputType: '0',
      pmsBalancePrice: 0,
      exTaxPrice: 0,
      taxPrice: 0,
      pmsInvTaxPrice: 0,
      pmsEstimatePrice: 0,
      currencyType: '',
      choiceTage: '',
      note: '',
      taxRateCode: '',
      supplierName: '',
      supplierCode: '',
    });
    popVisible.value = true;
  };
  const secretLevel = ref();
  const batchVisible = ref(false); // 批量上传
  const planListNo = ref();
  const formRef = ref();
  const execChange = async () => {
    const { data } = await execCalculate(addForm.value);
    if (data) {
      Object.assign(addForm.value, data);
    }
    console.log(data);
  };
  // 供应商联系人
  const vendorLinkManChange = (row: any) => {
    addForm.value.supplierLinkmanTel = row.phonePrivate;
  };
  const vendorLinkManTips = () => {
    Message.warning('请先选择供应商');
  };
  const changeSelect = () => {
    execChange();
  };
  const handleDelete = () => {
    Modal.warning({
      title: '请确认',
      content: '您确定要删除所选的数据？',
      hideCancel: false,
      onOk: async () => {
        await plansupplier(selectedKeys.value);
        Message.success('删除成功');
        getData();
      },
    });
  };
  const handleBid = () => {
    Modal.warning({
      title: '请确认',
      content: '您确定要中标所选的数据？',
      hideCancel: false,
      onOk: async () => {
        const { data } = await doWBid(selectedKeys.value);
        if (data) {
          Message.success('操作成功');
          getData();
        }
      },
    });
  };
  const handleCancelBid = () => {
    Modal.warning({
      title: '请确认',
      content: '您确定要中标所选的数据？',
      hideCancel: false,
      onOk: async () => {
        const { data } = await doNWBid(selectedKeys.value);
        if (data) {
          Message.success('操作成功');
          getData();
        }
      },
    });
  };
  const selectSupplier = (val) => {
    addForm.value.supplierName = val.supplierChinese;
    formRef.value.validateField('supplierCode');
  };
  const getData = async () => {
    renderData.value = [];
    const { data } = await pageByPlanListNo(planListNo.value);
    renderData.value = data.list;
    total.value = data.total;
    isLoadin.value = false;
  };
  const init = (val) => {
    planListNo.value = val.planListNo;
    secretLevel.value = val.secretLevel;
    getData();
  };
  const initColumns = (data: any[]) => {
    columns.value = lodash.cloneDeep(data);
    allColumns.value = lodash.cloneDeep(data);
  };
  const handleOk = async () => {
    const val = await formRef.value.validate();
    if (val) {
      return;
    }
    const { data } = await batchSaveOrUpdate({
      planListNo: planListNo.value,
      planSupplierVOList: [{ ...addForm.value }],
    });
    if (data) {
      Message.success('操作成功');
      handleCancel();
      getData();
    } else {
      Message.error('操作失败');
    }
  };
  // 批量上传
  const closeDrawer = (flag: boolean) => {
    console.log(flag, '关闭弹窗');
    batchVisible.value = flag;
  };

  // 批量上传后的完成事件
  const finish = async (flag: boolean) => {
    batchVisible.value = flag;
    getData();
  };
  const excelObj = ref({
    3: {
      api: exportBxcg,
      name: '比选采购导出数据',
      code: 'require_planBxcgUrl',
      importurl: '/api/procurement/require/excelOperation/importBxcg',
      exportUrl: 'http://10.191.5.215:9000/yiyan/比选采购明细导入模板.xlsx',
    },
    4: {
      api: exportCompeteNegotiation,
      name: '竞争性谈判采购导出数据',
      code: 'require_planJzxtpUrl',
      importurl:
        '/api/procurement/require/excelOperation/importCompeteNegotiation',
      exportUrl: 'http://10.191.5.215:9000/yiyan/竞争性谈判明细表导入模板.xlsx',
    },
    5: {
      api: exportZtb,
      name: '招投标导出数据',
      code: 'require_planZtbUrl',
      importurl: '/api/procurement/require/excelOperation/importZtb',
      exportUrl: 'http://10.191.5.215:9000/yiyan/招投标子表导入模板.xlsx',
    },
  });
  const handleExcel = () => {
    batchVisible.value = true;
  };
  // 导出
  const exportCpWzdapi = async () => {
    const { data, fileName } = await excelObj.value[activeRadio.value].api({
      planListNo: planListNo.value,
    });
    downFileToExcel(fileName, data);
    // try {
    //   const res = (await excelObj.value[activeRadio.value].api({
    //     planListNo: planListNo.value,
    //   })) as any;
    //   console.log(res);
    //   if (res.code === null || res.code === undefined) {
    //     const elink = document.createElement('a');
    //     elink.download = `${excelObj.value[activeRadio.value].name}.xlsx`;
    //     elink.style.display = 'none';
    //     const blob = new Blob([res], { type: 'application/vnd.ms-excel' });
    //     console.log(blob);
    //     elink.href = URL.createObjectURL(blob);
    //     document.body.appendChild(elink);
    //     elink.click();
    //     document.body.removeChild(elink);
    //   } else {
    //     // 正常情况下文件的下载是不会返回retCode的，如果发现有返回码，说明就是接口出了问题
    //     Notification.error({
    //       title: '导出失败！',
    //       content: res.message,
    //     });
    //   }
    // } catch (error) {
    //   // eslint-disable-next-line @typescript-eslint/no-unused-vars
    //   Notification.error({
    //     content: `出现异常！${error}`,
    //     closable: true,
    //     duration: 20000,
    //   });
    // }
  };
  const handleCancel = () => {
    popVisible.value = false;
  };
  const handleClose = () => {
    emit('update:viewDetailShow', false);
  };

  defineExpose({ init, tableRenderKeys, activeRadio });
</script>

<style lang="less" scoped>
  /deep/ .arco-picker {
    width: 100%;
  }

  .view-background {
    padding: 16px;
    background: #f7f9fc;
  }
</style>
